import {requests, requestsKimi} from '@/utils/requestApi.js';

async function createNewChat() {
    let data = {"name": "未命名会话", "is_example": false, "enter_method": "new_chat", "kimiplus_id": "kimi"};
    return await requestsKimi(`https://kimi.moonshot.cn/api/chat`, "POST", data)
}

async function* chat(question, chatId) {
    if (!chatId) {
        let response = await createNewChat();
        chatId = response.id;
    }

    console.log("chatId:", chatId)

    const url = 'https://kimi.moonshot.cn/api/chat/'+ chatId +'/completion/stream';
    const headers = {
        'Authorization': 'Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ1c2VyLWNlbnRlciIsImV4cCI6MTc1OTQ1ODQ1NSwiaWF0IjoxNzU2ODY2NDU1LCJqdGkiOiJkMnJxZjVzbnZqNGh0b2s2ZWlyZyIsInR5cCI6ImFjY2VzcyIsImFwcF9pZCI6ImtpbWkiLCJzdWIiOiJjb3YxOWlpdms2Z2ZpNG9lN3MzZyIsInNwYWNlX2lkIjoiY292MTlpaXZrNmdmaTRvZTdzMzAiLCJhYnN0cmFjdF91c2VyX2lkIjoiY292MTlpaXZrNmdmaTRvZTdzMmciLCJyb2xlcyI6WyJ2aWRlb19nZW5fYWNjZXNzIiwiIl0sInNzaWQiOiIxNzMwMzE0NjQyNzc5NDQ4NDMyIiwiZGV2aWNlX2lkIjoiNzU0MzU4NTc5MDI0MTE0MjUzNSIsInJlZ2lvbiI6ImNuIn0.yYHPt-XUavjUTmaNpduD17gStWciBb264QuHRsCQbQlq4vVinDzgraNUTO7NJ8MTuuBfP3JzeUQx24TiNb_Uug', // 替换为动态 Token
        'R-Timezone': 'Asia/Shanghai',
        'Content-Type': 'application/json',
    };

    const data = {
        messages: [{
            role: "user",
            content: question, // 传入问题
        }],
        use_search: true,
        extend: {
            sidebar: true,
        },
        kimiplus_id: "kimi",
        use_research: false,
        use_math: false,
        refs: [],
        refs_file: [],
    };

    try {
        const response = await fetch(url, {
            method: 'POST',
            headers,
            body: JSON.stringify(data),
        });

        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const reader = response.body?.getReader();
        if (!reader) {
            throw new Error("Response body is not readable.");
        }

        const decoder = new TextDecoder();
        let buffer = '';

        while (true) {
            const { done, value } = await reader.read();
            if (done) break;

            buffer += decoder.decode(value, { stream: true });
            let boundary = buffer.indexOf('\n');

            while (boundary !== -1) {
                const chunk = buffer.slice(0, boundary).trim();
                buffer = buffer.slice(boundary + 1);
                boundary = buffer.indexOf('\n');

                if (chunk.startsWith('data: ')) {
                    const jsonData = chunk.slice(6);
                    try {
                        const parsedData = JSON.parse(jsonData);
                        yield parsedData; // 实时返回数据给调用方
                    } catch (error) {
                        console.error('Failed to parse JSON:', error);
                    }
                }
            }
        }
    } catch (error) {
        console.error('Request failed:', error);
        throw error;
    }
}


export default {
    createNewChat,
    chat
}
